package wubj.com.tendencydemo.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;
import win.smartown.android.library.tableLayout.TableAdapter;
import win.smartown.android.library.tableLayout.TableLayout;
import wubj.com.tendencydemo.R;
import wubj.com.tendencydemo.base.BaseFragment;
import wubj.com.tendencydemo.bean.ColumnBean;

/**
 * chong.han 创建于 2017/6/1 0001.
 */
public class InfoFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private static String COLUMN_BEAN = "ColumnBean";
    private SwipeRefreshLayout swipeLayout;
    private LineChartView chart;
    private TableLayout tableLayout;
    private List<Content> contentList;
    private ColumnBean columnBean;
    private RadioButton rb_new_add;
    private RadioButton rb_start_user;
    private RadioButton rb_start_count;
    private RadioGroup rg_info;
    public TextView tv_chart_x;
    public TextView tv_chart_y;

    public static Fragment newInstance(ColumnBean bean) {
        Bundle args = new Bundle();
        args.putSerializable(COLUMN_BEAN, bean);
        InfoFragment fragment = new InfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void getIntentData(Bundle fragmentArgs) {
        columnBean = (ColumnBean) fragmentArgs.getSerializable(COLUMN_BEAN);
    }

    @Override
    public View initView(LayoutInflater inflater) {
        return View.inflate(getActivity(), R.layout.fragment_info, null);
    }

    @Override
    protected void initFindViewById(View view) {
        swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        rb_new_add = (RadioButton) view.findViewById(R.id.rb_new_add);
        rb_start_user = (RadioButton) view.findViewById(R.id.rb_start_user);
        rb_start_count = (RadioButton) view.findViewById(R.id.rb_start_count);
        tv_chart_x = (TextView) view.findViewById(R.id.tv_chart_x);
        tv_chart_y = (TextView) view.findViewById(R.id.tv_chart_y);
        rg_info = (RadioGroup) view.findViewById(R.id.rg_info);
        tableLayout = (TableLayout) view.findViewById(R.id.main_table);
        chart = (LineChartView) view.findViewById(R.id.chart);

    }

    int currentLine = 0;

    @Override
    public void initData() {
        swipeLayout.setRefreshing(true);

        initContent();
        firstRowAsTitle();

        generateValues(); //随机生成数据
        generateData();
        // Disable viewport recalculations, see toggleCubic() method for more info.
        chart.setViewportCalculationEnabled(false);
        chart.setValueSelectionEnabled(true);
        chart.setZoomEnabled(false);
        resetViewport();
    }

    final String[] fields = {"时间", "新增用户", "启动次数", "启动用户"};
    int dayHours = 24;
    int weekDay = 7;
    int monthDay = 30;

    private void initContent() {
        contentList = new ArrayList<>();
        contentList.add(new Content(fields[0], fields[1], fields[2], fields[3]));
        switch (columnBean.type) {
            case 1:
            case 2:
                numberOfPoints = dayHours;
                for (int i = 0; i < dayHours; i++) {
                    String time;
                    String time2;
                    if (i < 10) {
                        time = "0" + i + ":00-0" + i + ":59";
                        time2 = "0" + i + ":00";
                    } else {
                        time = i + ":00-" + i + ":59";
                        time2 = i + ":00";
                    }
                    mAxisXValues.add(new AxisValue(i).setLabel(time2));
                    contentList.add(new Content(time, newRandomNumber(), newRandomNumber(), newRandomNumber()));
                }
                break;
            case 3:
                numberOfPoints = weekDay;
                for (int i = 0; i < weekDay; i++) {
                    mAxisXValues.add(new AxisValue(i).setLabel(getStatetime(i, "MM/dd")));
                    contentList.add(new Content(getStatetime(i), newRandomNumber(), newRandomNumber(),
                            newRandomNumber()));
                }
                break;
            case 4:
                numberOfPoints = monthDay;
                for (int i = 0; i < monthDay; i++) {
                    mAxisXValues.add(new AxisValue(i).setLabel(getStatetime(i, "MM/dd")));
                    contentList.add(new Content(getStatetime(i), newRandomNumber(), newRandomNumber(),
                            newRandomNumber()));
                }
                break;
            case 5:
                for (int i = 0; i < 20; i++) {
                    mAxisXValues.add(new AxisValue(i).setLabel(getStatetime(i, "MM/dd")));
                    contentList.add(new Content(getStatetime(i), newRandomNumber(), newRandomNumber(),
                            newRandomNumber()));
                }
                break;
        }
    }

    public String getStatetime(int day, String format) {
        if (TextUtils.isEmpty(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 0 - day);
        Date monday = c.getTime();
        return sdf.format(monday);
    }

    public String getStatetime(int day) {
        return getStatetime(day, "yyyy-MM-dd");
    }

    //将第一行作为标题
    private void firstRowAsTitle() {
        //fields是表格中要显示的数据对应到Content类中的成员变量名，其定义顺序要与表格中显示的相同
        tableLayout.setAdapter(new TableAdapter() {
            @Override
            public int getColumnCount() {
                return fields.length;
            }

            @Override
            public String[] getColumnContent(int position) {
                int rowCount = contentList.size();
                String contents[] = new String[rowCount];
                try {
                    Field field = Content.class.getDeclaredField(fields[position]);
                    field.setAccessible(true);
                    for (int i = 0; i < rowCount; i++) {
                        contents[i] = (String) field.get(contentList.get(i));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return contents;
            }
        });
    }

    private String newRandomNumber() {
        return (new Random().nextInt(50) + 50) + "";
    }

    @Override
    public void onRefresh() {
        initData();
    }

    public static class Content {

        private String 时间;
        private String 新增用户;
        private String 启动次数;
        private String 启动用户;

        public Content(String 时间, String 新增用户, String 启动次数, String 启动用户) {
            this.时间 = 时间;
            this.新增用户 = 新增用户;
            this.启动次数 = 启动次数;
            this.启动用户 = 启动用户;
        }

        public String[] toArray() {
            return new String[]{时间, 新增用户, 启动次数, 启动用户};
        }
    }

    private LineChartData data;
    private int numberOfLines = 1;
    private int maxNumberOfLines = 3;
    private int numberOfPoints = 24;

    float[][] randomNumbersTab = null;

    private boolean hasAxes = true;
    private boolean hasAxesNames = false;
    private boolean hasLines = true;
    private boolean hasPoints = true;
    private ValueShape shape = ValueShape.CIRCLE;
    private boolean isFilled = true;
    private boolean hasLabels = false;
    private boolean isCubic = false;
    private boolean hasLabelForSelected = true;
    private boolean pointsHaveDifferentColor;
    private boolean hasGradientToTransparent = false;

    private List<AxisValue> mAxisXValues = new ArrayList<>();

    private void generateValues() {
        randomNumbersTab = new float[maxNumberOfLines][numberOfPoints];
        for (int i = 0; i < maxNumberOfLines; ++i) {
            for (int j = 0; j < numberOfPoints; ++j) {
                randomNumbersTab[i][j] = (float) Math.random() * 100f;
            }
        }
    }

//    private void reset() {
//        numberOfLines = 1;
//
//        hasAxes = true;
//        hasAxesNames = false;
//        hasLines = true;
//        hasPoints = true;
//        shape = ValueShape.CIRCLE;
//        isFilled = true;
//        hasLabels = false;
//        isCubic = false;
//        hasLabelForSelected = true;
//        pointsHaveDifferentColor = false;
//
//        chart.setValueSelectionEnabled(hasLabelForSelected);
//        resetViewport();
//    }

    private void resetViewport() {
        // Reset viewport height range to (0,100)
        final Viewport v = new Viewport(chart.getMaximumViewport());
        v.bottom = 0;
        v.top = 100;
        v.left = 0;
        v.right = numberOfPoints - 1;
        chart.setMaximumViewport(v);
        chart.setCurrentViewport(v);
        swipeLayout.setRefreshing(false);
    }

    private void generateData() {

        List<Line> lines = new ArrayList<Line>();

        List<PointValue> values = new ArrayList<PointValue>();
        for (int j = 0; j < numberOfPoints; ++j) {
            values.add(new PointValue(j, randomNumbersTab[currentLine][j]));
        }

        Line line = new Line(values);
        line.setColor(ChartUtils.COLORS[currentLine]);
        line.setShape(shape);
        line.setCubic(isCubic);
        line.setFilled(isFilled);
        line.setHasLabels(hasLabels);
        line.setHasLabelsOnlyForSelected(hasLabelForSelected);
        line.setHasLines(hasLines);
        line.setHasPoints(hasPoints);
//            line.setHasGradientToTransparent(hasGradientToTransparent);
        if (pointsHaveDifferentColor) {
            line.setPointColor(ChartUtils.COLORS[(currentLine + 1) % ChartUtils.COLORS.length]);
        }
        line.setStrokeWidth(1);
        line.setPointRadius(4);
        lines.add(line);

        data = new LineChartData(lines);

        if (hasAxes) {
            //坐标轴
            Axis axisX = new Axis(); //X轴
            axisX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
            axisX.setTextColor(Color.LTGRAY);  //设置字体颜色
            axisX.setTextSize(10);//设置字体大小
            axisX.setMaxLabelChars(8); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
            axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
            Axis axisY = new Axis().setHasLines(true);
            if (hasAxesNames) {
                axisX.setName("Axis X"); //表格名称
                axisY.setName("Axis Y");
            }
            data.setAxisXBottom(axisX);
            data.setAxisYLeft(axisY);
        } else {
            data.setAxisXBottom(null);
            data.setAxisYLeft(null);
        }

        data.setBaseValue(Float.NEGATIVE_INFINITY);
        chart.setLineChartData(data);
    }

    @Override
    protected void initListener() {
        chart.setOnValueTouchListener(new LineChartOnValueSelectListener() {
            @Override
            public void onValueSelected(int lineIndex, int pointIndex, PointValue value) {
//                ToastU.showSingleS("line:" + lineIndex + "point:" + pointIndex);
                tv_chart_x.setText(String.valueOf(mAxisXValues.get(pointIndex).getLabelAsChars()));
                tv_chart_y.setText(String.valueOf((int) value.getY()));
            }

            @Override
            public void onValueDeselected() {
            }
        });
        rg_info.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_new_add:
                        if (currentLine == 0) {
                            return;
                        }
                        currentLine = 0;
                        generateData();
                        break;
                    case R.id.rb_start_user:
                        if (currentLine == 1) {
                            return;
                        }
                        currentLine = 1;
                        generateData();
                        break;
                    case R.id.rb_start_count:
                        if (currentLine == 2) {
                            return;
                        }
                        currentLine = 2;
                        generateData();
                        break;
                }
            }
        });
//        pulltorefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
//            @Override
//            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
//                initData();
//            }
//        });
    }
}
